import crypto from 'crypto'
import service, { Base_API } from './utils/request'
var COS = require('cos-js-sdk-v5')
// 图片上传
var Bucket = 'daylong-1300427053'
var Region = 'ap-guangzhou'

const { uuid } = require('uuidv4')
/**
 * COS文件上传密钥
 * @param {*} key
 */

/**
 *
 * @param {Object} upload element upload的对象
 * @param {String} url  如果没有文件，将这个参数作为回调的参数
 * @param {function} folder 文件夹名称
 * @param {Object} _self 调用this对象
 * @param {function(url,_self)} callback 回调函数
 */
async function submitFileCOS(upload, url, folder, _self, callback) {
  if (upload.uploadFiles.length == 0) {
    callback('', _self)
    return
  }
  if (upload.uploadFiles[0].status == 'success') {
    callback(url.split(cosURL)[1], _self)
    return
  }
  var split = upload.uploadFiles[0].name.split('.')
  var Key = folder + uuid().replace('-', '') + '.' + split[split.length - 1]

  cos.putObject({
    Bucket: 'wonder-1300427053', /* 填入您自己的存储桶，必须字段 */
    Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
    Key: Key, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
    StorageClass: 'STANDARD',
    Body: upload.uploadFiles[0], // 上传文件对象
    onProgress: function(progressData) {
      console.log(JSON.stringify(progressData))
    }
  }, function(err, data) {
    console.log(err || data)
    var url = '/' + Key
    callback(url, _self)
  })
}

function message(_self, status, message) {
  if (this.status.error.indexOf(status) != -1) {
    _self.$message.error(message)
  } else if (this.status.success.indexOf(status) != -1) {
    _self.$message.success(message)
  } else if (this.status.info.indexOf(status) != -1) {
    _self.$message.info(message)
  }
}
/**
 * 深拷贝
 * @param {*} data 拷贝对象
 */
function deepCopy(data) {
  const type = Object.prototype.toString.call(data).split('[object ')[1].split(']')[0]
  switch (type) {
    case 'Boolean':
      return data
    case 'Number':
      return data
    case 'String':
      return data
    case 'Null':
      return data
    case 'Undefined':
      return data
    case 'Symbol':
      return data
    case 'Error':
      return data
    case 'RegExp':
      return data
    case 'Object':
      var obj = {}
      for (const key in data) {
        obj[key] = deepCopy(data[key])
      }
      return obj
    case 'Array':
      var array = []
      for (const i in data) {
        array[i] = deepCopy(data[i])
      }
      return array
    case 'Set':
      var set = new Set()
      for (const key of data) {
        set.add(deepCopy(key))
      }
      return set
    case 'Map':
      var map = new Map()
      var keys = data.keys()
      for (const key of keys) {
        map.set(key, deepCopy(data.get(key)))
      }
      return map
    case 'Math':
      var math = new Math()
      for (const name in data) {
        math[name] = deepCopy(data[name])
      }
      return math
    case 'JSON':
      var json = new JSON()
      for (const name in data) {
        json[name] = deepCopy(data[name])
      }
      return json
    case 'HTMLDocument':
      var htmlDocument = data
      for (var children in htmlDocument) {
        htmlDocument[children] = deepCopy(htmlDocument[children])
      }
      return htmlDocument
    case 'Window':
      var window = data
      for (var children in window) {
        window[children] = deepCopy(htmlDocument[children])
      }
      return window
  }
}

/**
 *  cos 文件上传
 */

const config = {
  Bucket: 'daylong-1300427053',
  Region: 'ap-guangzhou'
}

function getCos(tokenRes) {
  return new COS({
    getAuthorization: function(options, callback) {
      return new Promise((resolve, reject) => {
        // console.log('tokenRes', tokenRes, config)
        console.log(tokenRes, '这个是tokenRes')
        callback({
          TmpSecretId: tokenRes.data.tmpSecretId,
          TmpSecretKey: tokenRes.data.tmpSecretKey,
          XCosSecurityToken: tokenRes.data.sessionToken,
          StartTime: tokenRes.data.startTime, // 时间戳，单位秒，如：1580000000，建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
          ExpiredTime: tokenRes.data.expiredTime // 时间戳，单位秒，如：1580000000
          // ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
        })
      })
    },
    UploadCheckContentMd5: true
  })
}

/**
* 多文件上传cos
* @param {*} fileList 文件对象列表
* @param {*} folder  文件夹名称
*/
const submitFilesCOS = function(fileList, folder) {
  let file
  if (fileList && fileList.length) {
    file = fileList[0].file
  }
  const getToken = service.post(Base_API + '/upload_temporary_token')
  return new Promise((resolve, reject) => {
    if (!file) {
      resolve([])
      return
    }

    const split = file.name.split('.')
    const Key = folder + uuid().replace('-', '') + '.' + split[split.length - 1]
    getToken.then(res => {
      // 获取token成功创建cos
      const cos = getCos(res)
      cos.putObject({
        Bucket: config.Bucket, /* 填入您自己的存储桶，必须字段 */
        Region: config.Region, /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        // StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, function(err, data) {
        console.log(err, data)
        if (err) {
          reject(err)
          return
        }
        if (data) {
          resolve([Key])
        }
      })
    })
  })
}

export default {
  status: {
    success: [1],
    error: [0, 1001, 1002, 1014, 1015, 1028, 1029, 1115, 1125],
    info: [1005, 1006, 1026, 1027, 1030, 1072]
  },
  Bucket,
  Region,

  message,
  submitFileCOS,
  submitFilesCOS,
  deepCopy
  // canshu,
}
